package com.fate.securecheckplatform.ui.frags;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.fate.securecheckplatform.IDCard.IDCardManager;
import com.fate.securecheckplatform.IDCard.IDCardModel;
import com.fate.securecheckplatform.IDCard.IDUtil;
import com.fate.securecheckplatform.R;
import com.fate.securecheckplatform.SecureCheckApplication;
import com.fate.securecheckplatform.adapters.ObtainAdapter;
import com.fate.securecheckplatform.base.BaseFragment;
import com.fate.securecheckplatform.bean.EventEntity;
import com.fate.securecheckplatform.bean.TableForbiddenPerformance;
import com.fate.securecheckplatform.constant.Constant;
import com.fate.securecheckplatform.db.DataBase;
import com.fate.securecheckplatform.ui.acts.ObtainActivity;
import com.fate.securecheckplatform.utils.ExecutorManager;
import com.fate.securecheckplatform.utils.ToastUtil;
import com.fate.securecheckplatform.utils.Util;
import com.fate.securecheckplatform.views.RecyclerViewDivider;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import butterknife.BindView;
import butterknife.OnClick;

import static com.fate.securecheckplatform.constant.Constant.VID;

/**
 * Author:   RandBII
 * DATE:   2020/1/7
 * Description: 领取
 */
public class ObtainFragment extends BaseFragment {

    private static final String TAG = "ObtainFragment";

    @BindView(R.id.srl)
    SmartRefreshLayout mSrl;
    @BindView(R.id.rv)
    RecyclerView mRv;
    @BindView(R.id.et_card_num)
    EditText mEtCardNum;
    List<TableForbiddenPerformance> datas = new ArrayList<>();
    private ObtainAdapter adapter;
    private int page = 1;
    private int pageSize = 15;
    private int totalCount = 0;
    private DataBase dataBase;
    private int selecteItemPosition = -1;
    private String cardNum = "";
    // 身份证读取
    private IDCardManager manager;
    private ReadThread thread;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    IDUtil.play(1, 0);
                    ToastUtil.toast("读身份证成功！");
                    Bundle bundle = msg.getData();

                    String id = bundle.getString("id");

                    mEtCardNum.setText(id);
                    closeReadId();
                    break;
                case 1:

                    ToastUtil.toast("发现身份证!\n正在获取身份证数据...");
                    break;
                case 2:

                    break;
                case 3:

                    break;
                default:
                    break;
            }
        }

        ;
    };


    private Context mContext = null;
    private UsbManager mUsbManager = null;
    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Constant.ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        openDevice();
                    } else {
                        Toast.makeText(mContext, "USB未授权", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };

    public static ObtainFragment get() {
        ObtainFragment fragment = new ObtainFragment();
        Bundle bundle = new Bundle();
        bundle.putString("name", TAG);
        fragment.setArguments(bundle);
        return fragment;
    }

    private void ObtainFragment() {

    }

    @Override
    protected void initData() {

        Future<Integer> count = ExecutorManager.getService().submit(() -> dataBase.forbiddenObjectDao().getPerformancesCount());

        try {
            if (count.get() == null) {
                totalCount = 0;
            } else {
                totalCount = count.get();
            }
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 可以加载下一页
     *
     * @return
     */
    private boolean canLoadMore() {
        if (totalCount == 0) return false;
        return (pageSize * page < totalCount);
    }

    @Override
    protected void initView(View root) {
        IDUtil.initSoundPool(getActivity());
        EventBus.getDefault().register(this);
        mContext = SecureCheckApplication.get();
        dataBase = DataBase.getInstance(getActivity());
        datas = new ArrayList<>();
        mRv.setHasFixedSize(true);
        mRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        RecyclerViewDivider divider = new RecyclerViewDivider(getActivity());
        divider.setShowLastDivider(true);
        mRv.addItemDecoration(divider);
        adapter = new ObtainAdapter(getActivity(), datas);
        mRv.setAdapter(adapter);
        mSrl.setOnRefreshListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

                if (canLoadMore()) {
                    page++;
                    loadData();
                }

                if (mSrl != null) {
                    mSrl.finishLoadMore();
                }

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                loadData();
                if (mSrl != null) {
                    mSrl.finishRefresh();
                }
            }
        });

        adapter.setOnItemClickListener((view, position) -> {
            cancelAllSelected();
            selecteItemPosition = position;
            TableForbiddenPerformance p = datas.get(position);
            p.setAndroidSelected(true);
            adapter.notifyDataSetChanged();
        });

        mSrl.autoRefresh();


        mEtCardNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    loadData();
                } else {
                    searchPerformanceByID();
                }

            }
        });
        if (thread == null) {
            thread = new ReadThread();
            thread.start();
        }

    }

    private void cancelAllSelected() {
        if (datas != null) {
            for (TableForbiddenPerformance performance : datas) {
                performance.setAndroidSelected(false);
            }
        }
    }

    @Override
    protected int layoutResourceId() {
        return R.layout.fragment_obtian;
    }

    @OnClick({R.id.tv_read_card, R.id.tv_clear, R.id.tv_obtain})
    public void onClickEvnet(View v) {
        switch (v.getId()) {
            case R.id.tv_read_card:
                toReadCard();
                break;
            case R.id.tv_clear:
                mEtCardNum.setText("");
                break;
            case R.id.tv_obtain:
                if (selecteItemPosition == -1) {
                    ToastUtil.toast("请先选择一条信息");
                }
                navigateToObtain();
                break;
        }
    }

    /**
     * 开启读卡功能
     */
    private void toReadCard() {
        openDevice();
    }

    private void navigateToObtain() {
        if (selecteItemPosition == -1) {
            ToastUtil.toastShort("请先选择一条信息");
            return;
        }

        TableForbiddenPerformance performance = datas.get(selecteItemPosition);
        Intent intent = new Intent(getActivity(), ObtainActivity.class);
        intent.putExtra(Constant.DATA_OBTAIN, performance);
        startActivity(intent);

    }

    private void loadData() {


        try {
            Future<List<TableForbiddenPerformance>> future = ExecutorManager.getService().submit(() ->
                    dataBase.forbiddenObjectDao().getNotOutPerformances(Util.getPageStartCount(page, pageSize), pageSize));
            List<TableForbiddenPerformance> newPerformances = future.get();
            if (newPerformances != null ) {
                selecteItemPosition = -1;
                if (page == 1) {
                    datas.clear();
                }
                datas.addAll(newPerformances);
                adapter.notifyDataSetChanged();
            }
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询数据
     */
    private void searchPerformanceByID() {
        selecteItemPosition = -1;
        cardNum = mEtCardNum.getText().toString().trim();
        if (TextUtils.isEmpty(cardNum)) {
            return;
        }

        try {
            Future<List<TableForbiddenPerformance>> future = ExecutorManager.getService().submit(() -> dataBase.forbiddenObjectDao().getPerformancesByIDCard(cardNum));
            List<TableForbiddenPerformance> performances = future.get();

            if (performances != null && performances.size() > 0) {
                Log.e("->", "" + performances.get(0).getSfzh());
                datas.clear();
                datas.addAll(performances);
                adapter.notifyDataSetChanged();
            }

        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }

    }


    public void openDevice() {

        if (manager == null) {
            manager = new IDCardManager(getActivity());
        }
        startFlag = true;

    }

    private void requestDevicePermission() {
        mUsbManager = (UsbManager) Objects.requireNonNull(getActivity()).getSystemService(Context.USB_SERVICE);
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        mContext.registerReceiver(mUsbReceiver, filter);

        for (UsbDevice device : mUsbManager.getDeviceList().values()) {
            if (device.getVendorId() == VID && device.getProductId() == Constant.PID) {
                Intent intent = new Intent(Constant.ACTION_USB_PERMISSION);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
                mUsbManager.requestPermission(device, pendingIntent);
            }
        }
    }

    private void doStart() {

        requestDevicePermission();
    }


    @Override
    public void onDestroyView() {

        if (mUsbManager != null) {
            mContext.unregisterReceiver(mUsbReceiver);
        }
        super.onDestroyView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRecieveMessage(EventEntity entity) {
        if (entity.getCode() == Constant.CODE_REFRESH_OBTAIN_FRAGMENT) {
            selecteItemPosition = -1;
            if (mSrl != null)
                mSrl.autoRefresh();
        }
    }

    private boolean runFlag = true;
    private boolean startFlag = false;

    private class ReadThread extends Thread {
        @Override
        public void run() {
            while (runFlag) {
//                Log.e("AA---", "-");
                if (startFlag && manager != null) {
                    if (manager.findCard(200)) {
                        handler.sendEmptyMessage(1);
                        IDCardModel model = null;
                        long time = System.currentTimeMillis();

                        //获取身份证信息、图像
                        model = manager.getData(2000);
                        if (model != null) {
                            sendMessage(model.getName(), model.getSex(), model.getNation(),
                                    model.getYear(), model.getMonth(), model.getDay(),
                                    model.getAddress(), model.getIDCardNumber(), model.getOffice(),
                                    model.getBeginTime(), model.getEndTime(), model.getOtherData(),
                                    model.getPhotoBitmap(), "未读出指纹数据", "未读出指纹数据");
                        }

                    }
                }

                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            super.run();
        }

        private void sendMessage(String name, String sex, String nation,
                                 String year, String month, String day, String address, String id,
                                 String office, String start, String stop, String newaddress
                , Bitmap bitmap, String fp1, String fp2) {
            Message message = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("name", name);
            bundle.putString("sex", sex);
            bundle.putString("nation", nation);
            bundle.putString("year", year);
            bundle.putString("month", month);
            bundle.putString("day", day);
            bundle.putString("address", address);
            bundle.putString("id", id);
            bundle.putString("office", office);
            bundle.putString("begin", start);
            bundle.putString("end", stop);
            bundle.putString("newaddress", newaddress);
            bundle.putString("fp1", fp1);
            bundle.putString("fp2", fp2);

            message.setData(bundle);
            handler.sendMessage(message);
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        if (!pasue && manager != null) {
            pasue = true;
            manager.close();
            manager = null;
            startFlag = false;
        }
    }

    //app暂停
    private boolean pasue = false;

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (pasue) {
            pasue = false;
            if (manager == null) {
                manager = new IDCardManager(getActivity());
            }
            startFlag = true;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        closeReadId();
    }

    public void closeReadId() {
        startFlag = false;

        if (manager != null) {
            manager.close();
            manager = null;
        }
    }
}
